<template>
  <div class="zero-code-list">
    <a-spin :spinning="grid.loading">
      <vxe-grid
        class="subtable"
        v-if="!grid.loading"
        v-bind="grid"
        :ref="record.key"
      >
        <template #toolbar_buttons>
          <a-button
            type="link"
            icon="plus"
            @click="add"
            v-if="record.options.canAdd"
          >
            新增
          </a-button>
          <a-button type="link" icon="edit" v-if="record.options.canEdit">
            编辑</a-button
          >
          <a-popconfirm
            v-if="record.options.canDelete"
            title="确定删除数据?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="delAll"
          >
            <a-button type="link" v-if="record.options.canDelete">
              <a-icon type="delete" style="color: #ff4d4f"></a-icon>
              <span class="text-red"> 删除 </span>
            </a-button>
          </a-popconfirm>

          <a-button type="link" icon="import" v-if="record.options.canAdd">
            导入</a-button
          >
          <a-dropdown v-if="record.options.canReport">
            <a-menu slot="overlay">
              <a-menu-item key="1">
                <a-icon type="file-excel" />导出记录(excel)
              </a-menu-item>
              <a-menu-item key="2">
                <a-icon type="file-zip" />导出附件
              </a-menu-item>
              <a-menu-item key="3">
                <a-icon type="file-pdf" />导出PDF
              </a-menu-item>
            </a-menu>
            <a-button type="link" icon="download">
              导出
              <a-icon type="down" />
            </a-button>
          </a-dropdown>
        </template>
        <template #toolbar_tools> </template>
        <template #loading>
          <a-spin></a-spin>
        </template>
        <template #empty>
          <eip-empty />
        </template>
        <template #checkboxHeader="{ checked, indeterminate }">
          <span @click.stop="$refs[record.key].toggleAllCheckboxRow()">
            <a-checkbox :indeterminate="indeterminate" :checked="checked">
            </a-checkbox>
          </span>
        </template>
        <template #checkbox="{ row, checked, indeterminate }">
          <span @click.stop="$refs[record.key].toggleCheckboxRow(row)">
            <a-checkbox :indeterminate="indeterminate" :checked="checked">
            </a-checkbox>
          </span>
        </template>

        <template #operate="{ row }">
          <a-dropdown>
            <a-menu slot="overlay" @click="handleMenuClick">
              <a-menu-item key="1" v-if="record.options.canAdd">
                <a-tooltip title="复制">
                  <a-icon
                    @click="copy(row)"
                    type="copy"
                    class="eip-cursor-pointer"
                  ></a-icon
                  >复制
                </a-tooltip>
              </a-menu-item>
              <a-menu-item key="2" v-if="record.options.canEdit">
                <a-tooltip title="编辑">
                  <a-icon type="edit" class="eip-cursor-pointer"></a-icon
                  >编辑</a-tooltip
                >
              </a-menu-item>
              <a-menu-item key="3" v-if="record.options.canDelete">
                <a-popconfirm
                  title="确定删除数据?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="remove(row)"
                >
                  <a-tooltip title="删除">
                    <a-icon
                      type="delete"
                      style="color: red"
                      class="eip-cursor-pointer"
                    ></a-icon
                    >删除
                  </a-tooltip>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
            <a-icon type="more" :rotate="90" />
          </a-dropdown>
        </template>
        <!-- 序号 -->
        <template #seq="">
          <span>序号</span>
        </template>
        <template #edit="{ row, column }">
          <div
            v-for="(item, index) in columns.filter(
              (f) =>
                record.options.columns.includes(f.key) && column.field == f.key
            )"
            :key="index"
          >
            <component
              :is="'e' + item.type"
              :column="column"
              :row="row"
              :record="item"
              :recordSubtable="record"
              :valueSubtable="value"
              :formValue="formValue"
              :parentDisabled="parentDisabled"
              :worksheet="worksheet"
              :isEdit="true"
              :ref="column.field + row.RowId"
              :correlationDefault="correlationDefault"
              @change="subtableChange({ row, column })"
            ></component>
          </div>
        </template>
        <!-- 格式化内容 -->
        <template #default="{ row, column }">
          <div
            v-for="(item, index) in columns.filter(
              (f) =>
                record.options.columns.includes(f.key) && column.field == f.key
            )"
            :key="index"
          >
            <component
              :is="'e' + item.type"
              :column="column"
              :row="row"
              :record="item"
              :isEdit="false"
              :recordSubtable="record"
              :value="value"
              :formValue="formValue"
              :parentDisabled="parentDisabled"
              :worksheet="worksheet"
              :correlationDefault="correlationDefault"
              :ref="column.field + row.RowId"
            ></component>
          </div>
        </template>
      </vxe-grid>
    </a-spin>
  </div>
</template>
<script>
import { newGuid } from "@/utils/util";
import gridInput from "./grid/input.vue";
import gridTextarea from "./grid/textarea.vue";
import gridSwitch from "./grid/switch.vue";
import gridNumber from "./grid/number.vue";
import gridRadio from "./grid/radio.vue";
import gridSelect from "./grid/select.vue";
import gridCheckbox from "./grid/checkbox.vue";
import gridSys from "./grid/sys.vue";
import gridSerialNo from "./grid/serialNo.vue";
import gridCorrelation from "./grid/correlation.vue";
import gridFormulaNumber from "./grid/formulaNumber.vue";
import {
  findCorrelationRows,
  findCorrelationDefault,
  findById,
  businessDataById,
  findCorrelationDefaultField,
  findCorrelationDefaultWorkSheet,
} from "@/services/system/zerocode/run/edit";
export default {
  components: {
    einput: gridInput,
    etextarea: gridTextarea,
    eswitch: gridSwitch,
    eenumber: gridNumber,
    eeradio: gridRadio,
    eeselect: gridSelect,
    eecheckbox: gridCheckbox,
    esys: gridSys,
    eserialNo: gridSerialNo,
    ecorrelation: gridCorrelation,
    eformulaNumber: gridFormulaNumber,
  },
  data() {
    return {
      grid: {
        loading: true,
      },
      columns: [],
      nowValue: {
        RowId: null,
      },
      formValueDefault: {},
      correlationDefault: {}, //编辑时所有关联默认值
    };
  },
  props: ["record", "value", "formValue", "parentDisabled", "worksheet"],
  watch: {
    "record.options.columns": {
      handler: function (newVal, oldVal) {
        if (newVal.length != oldVal.length) {
          this.initColumn();
        }
      },
      deep: true,
    },
  },
  created() {
    this.initGridOption();
  },
  methods: {
    handleMenuClick() {},

    /**
     * 更改值状态
     */
    async subtableChange({ row, column }) {
      var key = column.field;
      this.nowValue = {
        RowId: row.RowId,
      };
      await this.handleChange(row[key], key);
      //计算公式
      this.setFormula();
      //得到数据
      var nowValueClone = this.$utils.clone(this.nowValue, true);
      var data = this.$utils.find(
        this.grid.data,
        (f) => f.RowId == nowValueClone.RowId
      );
      this.$utils.keys(nowValueClone).forEach((k) => {
        data[k] = nowValueClone[k];
      });
      // this.$refs[this.record.key].updateStatus({ row: data, column });
      this.handleInput();
    },
    /**
     * 更改值状态
     */
    async handleChange(value, key) {
      this.nowValue[key] = value;
      await this.reloadDefaultValue(key);
    },

    /**
     * 计算公式
     * @param key
     */
    setFormula() {
      let that = this;

      //赋予数据
      var data = this.$utils.find(
        this.grid.data,
        (f) => f.RowId == this.nowValue.RowId
      );
      this.$utils.keys(this.nowValue).forEach((k) => {
        data[k] = this.nowValue[k];
      });
      this.nowValue = data;

      var columnJson = this.columns;
      var columns = columnJson.filter(
        (f) => f.type == this.eipZeroCodeControl.formulaNumber
      );
      columns.forEach((item) => {
        var codeKeys = [];
        if (item.options.code) {
          const regex = /<div[^>]*>(.*?)<\/div>/g;
          const matches = item.options.code.match(regex);
          if (matches) {
            matches.forEach((matche) => {
              let div = that.stringToHtml(matche);
              var key = JSON.parse(div.lastChild.id).key;
              codeKeys.push(key);
              var regex = new RegExp(matche, "g");
              item.options.code = item.options.code.replace(regex, key);
            });
          }
          var keys = that.$utils.keys(that.nowValue);
          var params = "";
          keys.forEach((item) => {
            params +=
              "var " +
              item +
              "='" +
              (that.nowValue[item] ? that.nowValue[item] : 0) +
              "';";
          });
          codeKeys.forEach((item) => {
            //是否存在
            var keyFind = that.$utils.find(keys, (f) => f == item);
            if (keyFind == null) {
              params += "var " + item + "=0;";
            }
          });
          var evalJs = params + item.options.code;
          var value = 0;
          try {
            value = eval(evalJs);
          } catch (error) {}
          if (value != that.nowValue[item.key]) {
            that.nowValue[item.key] = value;

            that.setModel(item.key, value);
          }
        }
      });
    },

    /**
     * 字符串转Html
     * @param str
     */
    stringToHtml(str) {
      var parser = new DOMParser();
      var doc = parser.parseFromString(str, "text/html");
      return doc.body.firstChild;
    },
    /**
     * 重新加载
     * @param key
     */
    async reloadDefaultValue(key) {
      //得到所有与当前控件先关联控件
      var that = this;
      var reloadDefaultValueParents = await that.reloadDefaultValueParents(key);
      //是否为关联字段，若是则获取详情
      var columnJsonFind = that.$utils.find(this.columns, (f) => f.key == key);
      if (
        columnJsonFind &&
        columnJsonFind.type == this.eipZeroCodeControl.correlation
      ) {
        if (that.nowValue[key]) {
          var getResult = await businessDataById({
            zeroCodeId: columnJsonFind.options.zeroCodeId,
            id: that.nowValue[key],
          });
          that.setOptions(key, [getResult.data]);
          that.formValueDefault[key + that.eipZeroCodeSystemDetailKey] =
            getResult.data;
        } else {
          that.setOptions(key, []);
          that.formValueDefault[key + that.eipZeroCodeSystemDetailKey] = null;
        }
      }
      for (let index = 0; index < reloadDefaultValueParents.length; index++) {
        const item = reloadDefaultValueParents[index];
        //清空之前数据
        if (
          item.type == that.eipZeroCodeControl.correlation &&
          that.formValueDefault[item.key + that.eipZeroCodeSystemDetailKey]
        ) {
          that.formValueDefault[item.key + that.eipZeroCodeSystemDetailKey] =
            null;
        }
        that.nowValue[item.key] = undefined;
        await that.setDefaultValue(item, that.nowValue);
      }
    },

    /**
     * 默认值
     */
    async setDefaultValue(item, value) {
      await this.setDefalutCorrelation(item, value);
      await this.setDefalutInput(item, value);
      await this.setDefalutNumber(item, value);
    },

    /**
     * 初始化关联表默认值
     */
    async setDefalutCorrelation(item, value) {
      let that = this;
      if (item.type == that.eipZeroCodeControl.correlation) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.value:
            //单选，并且选择有默认值
            if (
              item.options.type ==
                that.eipZeroCodeControlCorrelationType.single &&
              item.options.defaultValueConfig.field.length > 0
            ) {
              value[item.key] = item.options.defaultValueConfig.field[0].key;
            } else if (
              item.options.type ==
                that.eipZeroCodeControlCorrelationType.multiple &&
              item.options.defaultValueConfig.field.length > 0
            ) {
              value[item.key] = item.options.defaultValueConfig.field.map(
                (f) => f.key
              );
            }
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            let result = await findCorrelationDefaultField({
              zeroCodeId: this.options.zeroCodeId,
              key: item.key,
            });
            if (result.code == that.eipResultCode.success) {
              value[item.key] = result.data.data.map((f) => f.RowId);
              that.dynamicData[item.key] = result;
            }
            break;
          case that.eipZeroCodeDefaultType.field:
            //判断字段是否有值
            if (
              item.options.type ==
                that.eipZeroCodeControlCorrelationType.single &&
              item.options.defaultValueConfig.field.length > 0
            ) {
              //是否有值
              var nowKey =
                item.options.defaultValueConfig.field[0].correlation.key;
              if (value[nowKey]) {
                //获取详情
                var getResultData =
                  that.formValueDefault[
                    item.options.defaultValueConfig.field[0].correlation.key +
                      that.eipZeroCodeSystemDetailKey
                  ];
                //赋予值
                var correctionValue =
                  getResultData[item.options.defaultValueConfig.field[0].key];
                var parseValue = JSON.parse(correctionValue).join(",");

                await that.setDataAndChange(item.key, parseValue);
              } else {
                await that.setDataAndChange(item.key, null);
              }
            } else if (
              item.options.type ==
                that.eipZeroCodeControlCorrelationType.multiple &&
              item.options.defaultValueConfig.field.length > 0
            ) {
            }
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
        }
      }
    },

    /**
     * 初始化数字框默认值
     */
    async setDefalutNumber(item, value) {
      let that = this;
      if (
        item.options.defaultValueConfig &&
        item.type == that.eipZeroCodeControl.number
      ) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.field:
            if (item.options.defaultValueConfig.field.length > 0) {
              var getResultData =
                that.formValueDefault[
                  item.options.defaultValueConfig.field[0].correlation.key +
                    that.eipZeroCodeSystemDetailKey
                ];
              //赋予值
              var correctionValue = "";
              if (getResultData) {
                correctionValue =
                  getResultData[item.options.defaultValueConfig.field[0].key];
              }
              await that.setDataAndChange(item.key, correctionValue);
            }
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            //查询工作表
            let result = await findCorrelationDefaultWorkSheet({
              zeroCodeId: that.record.options.zeroCodeId,
              key: item.key,
              values: that.getFormValue(),
            });
            var correctionValue = "";
            if (result.code == that.eipResultCode.success) {
              //判断是否具有值
              if (
                result.data &&
                result.data.data &&
                result.data.data.length == 1
              ) {
                correctionValue =
                  result.data.data[0][
                    item.options.defaultValueConfig.worksheet.setKey
                  ];
              }
            }
            await that.setDataAndChange(item.key, correctionValue);
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
          case that.eipZeroCodeDefaultType.value:
            value[item.key] = item.options.defaultValue;
            break;
        }
      }
    },

    /**
     * 初始化文本框默认值
     */
    async setDefalutInput(item, value) {
      let that = this;
      if (
        item.options.defaultValueConfig &&
        item.options.defaultValueConfig.code &&
        (item.type == that.eipZeroCodeControl.input ||
          item.type == that.eipZeroCodeControl.textarea)
      ) {
        switch (item.options.defaultValueConfig.type) {
          case that.eipZeroCodeDefaultType.field:
            //查询引用的字段
            var keys = that.getDefaultCodeKeys(
              item.options.defaultValueConfig.code
            );
            //关联字段值
            let correctionValueObj = {};
            if (keys.length > 0) {
              for (let index = 0; index < keys.length; index++) {
                const kitem = keys[index];
                //关联表
                var correctionValue = "";
                if (kitem.zeroCodeId) {
                  var getResultData =
                    that.formValueDefault[
                      kitem.field + that.eipZeroCodeSystemDetailKey
                    ];
                  //赋予值
                  if (getResultData) {
                    correctionValue = getResultData[kitem.key];
                  }
                }
                correctionValueObj[
                  kitem.key + kitem.zeroCodeId.replace(/-/g, "")
                ] = correctionValue;
              }
            }
            let content = this.getDefaultCodeContent(
              item.options.defaultValueConfig.code,
              value,
              correctionValueObj
            );
            value[item.key] = content;
            await that.setDataAndChange(item.key, content);
            break;
          case that.eipZeroCodeDefaultType.worksheet:
            //查询工作表
            break;
          case that.eipZeroCodeDefaultType.fun:
            break;
        }
      }
    },

    /**
     * 赋予值并继续触发改变
     */
    async setDataAndChange(key, value) {
      await this.handleChange(value, key);
    },
    /**
     * 重新加载
     * @param key
     */
    async reloadDefaultValueParents(key) {
      let that = this;
      let keys = [];
      var columnJson = this.columns;
      for (let index = 0; index < columnJson.length; index++) {
        const element = columnJson[index];
        that.findDefaultValueKey(element, key, keys);
      }
      //去重
      keys = that.$utils.uniq(keys, (item) => item.key);
      //检测keys是否还具有依赖，避免再次修改值，又触发一次
      var deleteKeys = [];
      for (let indexi = 0; indexi < keys.length; indexi++) {
        let keyNow = keys[indexi];
        //循环后面的
        for (let indexj = indexi + 1; indexj < keys.length; indexj++) {
          that.findDefaultValueKey(keys[indexj], keyNow.key, deleteKeys);
        }
      }

      //删除keys
      deleteKeys.forEach((item) => {
        that.$utils.remove(keys, (f) => f.key == item.key);
      });

      return keys;
    },
    /**
     * 根据传入的对象和对应的key查询是否需要添加到触发关联
     * @param element
     * @param key
     */
    findDefaultValueKey(element, key, keys) {
      let that = this;

      if (element.type == that.eipZeroCodeControl.otherField) {
        if (element.options.key == key) {
          keys.push(element);
        }
      } else if (
        element.options.defaultValueConfig &&
        element.options.defaultValueConfig.type
      ) {
        //默认值为字段
        if (
          element.options.defaultValueConfig.type ==
          that.eipZeroCodeDefaultType.field
        ) {
          if (element.type == that.eipZeroCodeControl.input) {
            var getDefaultCodeKeys = that.getDefaultCodeKeys(
              element.options.defaultValueConfig.code
            );
            if (
              getDefaultCodeKeys.map((m) => m.key).includes(key) ||
              getDefaultCodeKeys.map((m) => m.field).includes(key)
            ) {
              keys.push(element);
            }
          } else {
            var getFieldKeys = that.$utils.find(
              element.options.defaultValueConfig.field,
              (f) =>
                f.key == key ||
                (f.correlation ? f.correlation.key == key : false)
            );
            if (getFieldKeys) {
              keys.push(element);
            }
          }
        }

        //默认值为工作表
        else if (
          element.options.defaultValueConfig.type ==
          that.eipZeroCodeDefaultType.worksheet
        ) {
          //解析表达式
          const traverseFilterParents = (filter) => {
            //处理字段查询明细
            if (filter.rules != null && filter.rules.length > 0) {
              filter.rules.forEach((item) => {
                if (
                  item.field &&
                  item.op &&
                  item.opType == this.eipZeroCodeFormSettingOpType.variable
                ) {
                  if (item.data == key) {
                    keys.push(element);
                  }
                }
              });

              //处理嵌套查询
              if (filter.groups != null && filter.groups.length > 0) {
                filter.groups.forEach((item) => {
                  traverseFilterParents(item);
                });
              }
            }
          };

          traverseFilterParents(
            element.options.defaultValueConfig.worksheet.filters
          );
        }
      }
    },
    /**
     * 获取提交数据
     */
    getFormValue() {
      let that = this;
      let values = [];
      that.columns.forEach((columnObj) => {
        var value = that.nowValue[columnObj.key];
        var options = undefined;
        var array = [];
        switch (columnObj.type) {
          case that.eipZeroCodeControl.checkbox:
            options = columnObj.options.options;
            if (value) {
              value.map((m) => {
                array.push(m);
              });
              values.push({
                key: columnObj.key,
                value: array.length > 0 ? JSON.stringify(array) : null,
              });
            }
            break;
          case that.eipZeroCodeControl.select:
            options = columnObj.options.options;
            if (columnObj.options.multiple && value) {
              value.map((m) => {
                array.push(m);
              });
            } else {
              array.push(value);
            }
            values.push({
              key: columnObj.key,
              value: array.length > 0 ? JSON.stringify(array) : null,
            });
            break;
          case that.eipZeroCodeControl.radio:
            options = columnObj.options.options;
            if (value) {
              array.push(value);
              values.push({
                key: columnObj.key,
                value: array.length > 0 ? JSON.stringify(array) : null,
              });
            }
            break;
          case that.eipZeroCodeControl.correlation:
            if (value) {
              //单选
              if (
                columnObj.options.type ==
                that.eipZeroCodeControlCorrelationType.single
              ) {
                array.push(value);
              } else {
                //是否为表格模式
                if (
                  columnObj.options.showType ==
                  that.eipZeroCodeControlCorrelationShowType.grid
                ) {
                  value.map((m) => {
                    array.push(m.RowId);
                  });
                } else {
                  value.map((m) => {
                    array.push(m);
                  });
                }
              }
            }
            values.push({
              key: columnObj.key,
              value: JSON.stringify(array),
            });
            break;
          case that.eipZeroCodeControl.subtable:
            if (value) {
              value.forEach((fvitem) => {
                //变成key,value数组
                var arrayItem = [];
                var keys = that.$utils.keys(fvitem);
                keys
                  .filter((f) => f != "_X_ROW_KEY")
                  .forEach((kitem) => {
                    arrayItem.push({
                      key: kitem,
                      value: fvitem[kitem],
                    });
                  });
                array.push({
                  rowId: arrayItem.filter((f) => f.key == "RowId")[0].value,
                  data: arrayItem,
                });
              });
            }
            values.push({
              key: columnObj.key,
              value: JSON.stringify(array),
            });
            break;
          case that.eipZeroCodeControl.textCombination:
            break;
          case that.eipZeroCodeControl.otherField:
          case that.eipZeroCodeControl.formulaNumber:
            values.push({
              key: columnObj.key,
              value: value,
            });
            break;
          case "treeSelect":
            break;
          case "cascader":
            break;
          case that.eipZeroCodeControl.district:
            options = columnObj.options.options;
            options = that.$utils.toTreeArray(options);
            options = options.filter((f) => value.includes(f.value));
            options.forEach((item) => {
              array.push({
                label: item.label,
                value: item.value,
              });
            });
            values.push({
              key: columnObj.key,
              value: array.length > 0 ? JSON.stringify(array) : null,
            });
            break;
          case that.eipZeroCodeControl.dictionary:
            if (value) {
              if (columnObj.options.dictionaryShowType == 2) {
                values.push({
                  key: columnObj.key,
                  value: JSON.stringify([value]),
                });
              }
              if (columnObj.options.dictionaryShowType == 3) {
                values.push({
                  key: columnObj.key,
                  value: JSON.stringify(value),
                });
              }
            }
            break;
          case that.eipZeroCodeControl.user:
          case that.eipZeroCodeControl.organization:
            break;
          case that.eipZeroCodeControl.map:
            values.push({
              key: columnObj.key,
              value: value,
            });
            break;
          case that.eipZeroCodeControl.uploadFile:
          case that.eipZeroCodeControl.uploadImg:
            values.push({
              key: columnObj.key,
              value: JSON.stringify(value),
            });
            break;
          case that.eipZeroCodeControl.serialNo:
            break;
          default:
            values.push({
              key: columnObj.key,
              value: value,
            });
            break;
        }
      });
      return JSON.stringify(values);
    },

    /**
     *给关联表赋予默认下拉值
     */
    setOptions(key, data) {
      var options = {
        data: {
          data: data,
        },
      };
      var refKey = key + this.nowValue.RowId;
      var ref = this.$refs[refKey];
      if (ref && ref.length > 0) {
        ref[0].setOptions(options);
        ref[0].setModel(data.map((m) => m.RowId));
      }
    },

    /**
     *
     * @param key
     * @param data
     */
    setModel(key, data) {
      var refKey = key + this.nowValue.RowId;
      var ref = this.$refs[refKey];
      if (ref && ref.length > 0) {
        ref[0].setModel(data);
      }
    },

    /**
     * 改变事件
     */
    handleInput() {
      this.$emit("change", this.grid.data);
    },

    /**
     *
     */
    getOptions(field) {
      return this.$utils.find(
        this.record.options.columns,
        (f) => f.key == field
      );
    },
    /**
     *初始化列表配置项
     */
    initGridOption() {
      this.grid = {
        id: "correlation-grid",
        editConfig: {
          trigger: "click",
          mode: "cell",
          beforeEditMethod({ row, rowIndex, column, columnIndex }) {
            return true;
          },
        },
        loading: true,
        seqConfig: {},
        printConfig: {},
        exportConfig: {},
        cellClassName({ row, column }) {
          if (column.editRender && !column.editRender.enabled) {
            return "col-enabled";
          }
          return null;
        },
        filterConfig: {
          remote: true,
        },
        customConfig: {
          mode: "popup",
        },
        sortConfig: {
          trigger: "cell",
          defaultSort: {},
          orders: ["desc", "asc", null],
          remote: true,
          multiple: true,
          chronological: true,
        },
        toolbarConfig: {
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools",
          },
        },
        columns: [],
        data: [],
        extend: {
          id: null,
        },
      };
      //判断是否
      this.initColumn();
    },

    /**
     * 初始化列
     */
    initColumn() {
      let that = this;
      this.grid.columns = [];
      this.grid.columns.push({
        type: "checkbox",
        width: 50,
        align: "center",
        fixed: "left",
        resizable: false,
        slots: {
          checkbox: "checkbox",
          header: "checkboxHeader",
        },
      });
      this.grid.columns.push({
        title: "操作",
        field: "operate",
        width: 50,
        align: "center",
        fixed: "left",
        slots: {
          default: "operate",
        },
      });
      this.grid.columns.push({
        type: "seq",
        width: 50,
        fixed: "left",
        resizable: false,
        slots: {
          header: "seq",
        },
      });

      //获取
      findById(this.record.options.zeroCodeId).then(function (result) {
        that.columns = JSON.parse(result.data.columnJson);
        that.columns
          .filter((f) => that.record.options.columns.includes(f.key))
          .forEach((element) => {
            let column = {
              field: element.key,
              title: element.label,
              width: element.width,
              sortable: true,
              slots: {
                edit: "edit",
              },
              editRender: {
                enabled: that.record.options.canEdit,
              },
              showOverflow: "ellipsis",
              filterRender: {
                name: "MLFilterRender",
              },
              filters: [
                {
                  data: {
                    type: "input",
                    key: null,
                    op: "cn",
                    write: null,
                    options: [],
                  },
                },
              ],
            };
            var sysFind = that.$utils.find(
              that.eipSystemFiled,
              (f) => f.key == element.key
            );
            if (sysFind) {
              //判断是否为系统字段
              switch (element.key) {
                case "CreateTime":
                case "UpdateTime":
                  column.filters = [
                    {
                      data: {
                        type: "datetime",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  that.grid.columns.push(column);
                  break;
                case "RowId":
                  column.filters = [
                    {
                      data: {
                        type: "input",
                        key: null,
                        op: "cn",
                        write: null,
                        options: [],
                      },
                    },
                  ];
                  that.grid.columns.push(column);
                  break;
                case "CreateUser":
                case "UpdateUser":
                  column.filters = [
                    {
                      data: {
                        type: "user",
                        op: "cn",
                        write: null,
                      },
                    },
                  ];
                  column.slots.default = "default";
                  that.grid.columns.push(column);
                  break;
              }
            } else {
              switch (element.type) {
                case that.eipZeroCodeControl.radio:
                case that.eipZeroCodeControl.checkbox:
                case that.eipZeroCodeControl.select:
                  let options = [];
                  element.options.options.forEach((item) => {
                    options.push({
                      value: item.value,
                      label: item.label,
                      checked: false,
                      color: element.options.optionsColor ? item.color : null,
                    });
                  });
                  column.filters = [
                    {
                      data: {
                        type: "select",
                        key: null,
                        op: "jcn",
                        write: null,
                        options: options,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.number:
                  column.filters = [
                    {
                      data: {
                        type: "number",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.switch:
                  column.filters = [
                    {
                      data: {
                        type: "switch",
                        key: null,
                        op: "cn",
                        write: null,
                        options: [
                          {
                            value: 1,
                            label: "是",
                            checked: false,
                            color: "red",
                          },
                          {
                            value: 0,
                            label: "否",
                            checked: false,
                            color: "#1890ff",
                          },
                        ],
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.rate:
                  column.filters = [
                    {
                      data: {
                        type: "number",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.slider:
                  column.filters = [
                    {
                      data: {
                        type: "number",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.uploadFile:
                case that.eipZeroCodeControl.uploadImg:
                  break;
                case that.eipZeroCodeControl.editor:
                  column.type = "html";
                  break;
                case that.eipZeroCodeControl.date:
                  column.filters = [
                    {
                      data: {
                        type: "datetime",
                        op: "cn",
                        write: null,
                        min: null,
                        max: null,
                      },
                    },
                  ];
                  break;
                case that.eipZeroCodeControl.formulaNumber:
                  column.editRender.enabled = false;
                  break;
              }
              if (element.type != that.eipZeroCodeControl.editor) {
                column.slots.default = "default";
              }
              that.grid.columns.push(column);
            }
          });
        setTimeout(function () {
          that.grid.loading = false;
          that.initGridData();
        }, 100);
      });
    },

    /**
     * 新增
     */
    add() {
      const data = {};
      var showColumns = this.columns.filter((f) =>
        this.record.options.columns.includes(f.key)
      );
      for (let index = 0; index < showColumns.length; index++) {
        const item = showColumns[index];
        data[item.key] = item.options.defaultValue;
      }
      this.grid.data.push({
        ...data,
        RowId: newGuid(),
      });
      //数据源获取
      this.handleInput();
    },
    /**
     * 移除
     * @param {*} item
     */
    remove(item) {
      const index = this.grid.data.indexOf(item);
      if (index !== -1) {
        this.grid.data.splice(index, 1);
      }
      //数据源获取
      this.handleInput();
    },

    /**
     * 删除
     */
    delAll() {
      let that = this;
      let nowChosen = this.$refs[this.record.key].getCheckboxRecords(true);
      //获取其他页显示项
      let otherChosen =
        this.$refs[this.record.key].getCheckboxReserveRecords(true);
      var data = nowChosen.concat(otherChosen);
      //判断是否选择了数据
      if (data.length == 0) {
        this.$message.error("请选择数据");
        return;
      }
      data.forEach((item) => {
        that.remove(item);
      });
    },

    /**
     * 复制数据
     * @param {*} record
     */
    copy(record) {
      const data = {};
      var showColumns = this.columns.filter((f) =>
        this.record.options.columns.includes(f.key)
      );
      showColumns.forEach((item) => {
        data[item.key] = record[item.key];
      });
      const index = this.grid.data.indexOf(record);
      data.RowId = newGuid();
      this.grid.data.splice(index + 1, 0, data);
      this.handleInput();
    },

    /**
     * 初始化数据
     */
    initGridData() {
      let that = this;
      if (this.worksheet.mode == this.eipZeroCodeWorkSheetMode.edit) {
        findCorrelationRows({
          zeroCodeId: this.worksheet.zeroCodeId,
          key: this.record.key,
          rowId: this.worksheet.rowId,
        }).then((resultTable) => {
          //数据加工
          resultTable.data.data.forEach((res) => {
            var keys = that.$utils.keys(res);
            keys.forEach((k) => {
              var columnsFind = that.$utils.find(
                that.columns,
                (f) => f.key == k
              );
              if (
                columnsFind &&
                columnsFind.type == that.eipZeroCodeControl.correlation
              ) {
                var value = res[k];
                if (value) {
                  var valueJson = JSON.parse(value);
                  var dynamicData = [];
                  //判断是单选还是多选
                  if (
                    columnsFind.options.type ==
                    this.eipZeroCodeControlCorrelationType.multiple
                  ) {
                    res[k] = valueJson.map((m) => m.RowId);
                  } else {
                    res[k] = valueJson.map((m) => m.RowId).join(",");
                  }
                  //赋予options
                  valueJson.forEach((vj) => {
                    dynamicData.push({
                      label: vj.Title,
                      showLabel: [vj.Title],
                      labels: [
                        {
                          column: null,
                          label: vj.Title,
                        },
                      ],
                      value: vj.RowId,
                    });
                  });
                  that.correlationDefault[k + res.RowId] = dynamicData;
                }
              }
            });
          });
          resultTable.data.data.forEach((res) => {
            that.grid.data.push(res);
          });
          that.handleInput();
        });
      } else if (this.worksheet.mode == this.eipZeroCodeWorkSheetMode.add) {
        //获取默认值
        findCorrelationDefault({
          zeroCodeId: this.worksheet.zeroCodeId,
          key: this.record.key,
          rowId: this.worksheet.rowId,
        }).then((resultTable) => {
          resultTable.data.data.forEach((res) => {
            that.grid.data.push(res);
          });
        });
      }
    },

    /**
     *获取代码先关联的Key
     * @param content
     */
    getDefaultCodeKeys(content) {
      //解析默认值
      let keys = [];
      const tempDiv = document.createElement("div");
      // 设置div的内容为HTML字符串
      tempDiv.innerHTML = content;
      // 查询所有的span标签
      const divs = tempDiv.querySelectorAll("div");
      for (let index = 0; index < divs.length; index++) {
        const div = divs[index];
        const span = div.querySelectorAll("span")[0];
        var parseData = JSON.parse(decodeURI(span.id));
        keys.push(parseData);
      }
      return keys;
    },

    /**
     * 获取带有代码值的内容
     * @param defaultValue
     */
    getDefaultCodeContent(content, value, correctionValue) {
      //解析默认值
      let that = this;
      const tempDiv = document.createElement("div");
      // 设置div的内容为HTML字符串
      tempDiv.innerHTML = content;
      // 查询所有的span标签
      const divs = tempDiv.querySelectorAll("div");
      divs.forEach((div) => {
        const span = tempDiv.querySelectorAll("span")[0];
        var parseData = JSON.parse(decodeURI(span.id));
        var key = parseData.key;
        switch (key) {
          case "CreateUserId":
            content = content.replaceAll(div.outerHTML, that.user.userId);
            break;
          case "CreateUserName":
            content = content.replaceAll(div.outerHTML, that.user.name);
            break;
          case "CreateOrganizationId":
            content = content.replaceAll(
              div.outerHTML,
              that.user.organizationId
            );
            break;
          case "CreateOrganizationName":
            content = content.replaceAll(
              div.outerHTML,
              that.user.organizationName
            );
            break;
          default:
            if (parseData.zeroCodeId) {
              key = key + parseData.zeroCodeId.replace(/-/g, "");
              content = content.replaceAll(
                div.outerHTML,
                that.$utils.isUndefined(correctionValue[key])
                  ? ""
                  : correctionValue[key]
              );
            } else {
              content = content.replaceAll(
                div.outerHTML,
                that.$utils.isUndefined(value[key]) ? "" : value[key]
              );
            }
            break;
        }
      });
      return content;
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .col-enabled {
  background-color: #f5f5f5 !important;
}
</style>
